import axios from 'axios'
import { io } from 'socket.io-client'


// API基础URL
const API_BASE_URL = 'http://localhost:3010'

// Socket.IO 连接实例
let socket = null

// 创建axios实例
const request = axios.create({
  baseURL: API_BASE_URL,
  timeout: 30000, 
  headers: {
    'Content-Type': 'application/json',
  },
  withCredentials: true 
})

// 请求拦截器
request.interceptors.request.use(
  (config) => {
    // 从localStorage获取token
    const token = localStorage.getItem('accessToken')
    if (token && config.headers) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  }
)

// 响应拦截器
request.interceptors.response.use(
  response => response,
  error => {
    // 401错误时跳转登录页
    if (error.response?.status === 401) {
      localStorage.removeItem('accessToken');
      window.location.href = '/login';
    }
    return Promise.reject(error);
  }
);

// 登录API
export const login = async (data = {}) => {
  return request.post('/auth/login', data)
}

// 发送邮箱验证码API
export const sendEmail = async (data = {}) => {
  return request.post('/auth/send-code', data)
}

// 注册API
export const register = async (data = {}) => {
  return request.post('/auth/verify-register', data)
}

// 获取用户信息
export const getUser = async () => {
  return request.get('/auth/me')
}

// 登出
export const logout = async () => {
  return request.post('/auth/logout')
}

//获取商品总数
export const getProductTotal = async () => {
  return request.get('/products/total-count')
}

//获取公告列表
export const getAnnouncementList = async (data = {}) => {
  return request.get('/announcement/list',data)
}

//添加公告
export const addAnnouncement = async (data = {}) => {
  return request.post('/announcement/add', data)
}

//更新公告
export const updateAnnouncement = async (data = {}) => {
  return request.post('/announcement/up', data)
}

//删除公告
export const deleteAnnouncement = async (data = {}) => {
  return request.post('/announcement/del', data)
}

//获取所有的商户数据
export const getAllMerchants = async (params = {}) => {
  return request.get('/auth/all-merchants', { params })
}

// 获取商品列表
export const getProductList = async (params = {}) => {
  return request.get('/products/list', { params })
}

// 添加商品
export const addProduct = async (data = {}) => {
  return request.post('/products/add', data)
}

// 删除商品
export const deleteProduct = async (id, data = {}) => {
  return request.delete(`/products/delete/${id}`, { data })
}

// 修改商品
export const updateProduct = async (id, data = {}) => {
  return request.post(`/products/update/${id}`, data)
}

// 获取商户详情
export const getMerchantDetail = async (id) => {
  return request.get(`/auth/merchant/${id}`)
}

// 冻结商户
export const freezeMerchant = async (id) => {
  return request.post(`/auth/merchant/freeze/${id}`)
}

// 解冻商户
export const unfreezeMerchant = async (id) => {
  return request.post(`/auth/merchant/unfreeze/${id}`)
}

// 审核商户
export const approveMerchant = async (id) => {
  return request.post(`/auth/merchant/approve/${id}`)
}

// 获取平台总销售量
export const getTotalSalesVolume = async () => {
  return request.get('/products/total-sales-volume')
}

// 获取平台用户总数
export const getTotalUsers = async () => {
  return request.get('/auth/total-users')
}

// 获取H用户总数
export const getHTotalUsers = async () => {
  return request.get('/huser/total-users')
}

// 获取平台总销售额
export const getTotalSales = async () => {
  return request.get('/products/total-sales')
}

// 获取商户总数
export const getTotalMerchants = async () => {
  return request.get('/auth/total-merchants')
}

// 获取商品分类分布
export const getCategoryDistribution = async () => {
  return request.get('/products/category-distribution')
}

// 获取商品类别销量数据
export const getCategorySalesData = async () => {
  return request.get('/products/category-sales')
}

// 获取订单列表
export const getOrderList = async (params = {}) => {
  return request.get('/order/list', { params })
}

// 获取按省份分组的订单数据
export const getOrdersByProvince = async () => {
  return request.get('/order/by-province')
}

// 获取按年份和月份分组的订单数据
export const getOrdersByYearMonth = async () => {
  return request.get('/order/by-year-month')
}

// 更新订单状态
export const updateOrderStatus = async (id, status) => {
  return request.post(`/order/update/${id}`, { status })
}

// Socket.IO 相关函数

// 初始化 Socket.IO 连接
export const initSocket = (userId) => {
  if (!socket) {
    socket = io(API_BASE_URL)
    
    // 连接成功后发送用户ID
    socket.on('connect', () => {
      console.log('Socket.IO 连接成功')
      if (userId) {
        socket.emit('login', userId)
      }
    })
    
    // 连接错误处理
    socket.on('connect_error', (error) => {
      console.error('Socket.IO 连接失败:', error)
    })
  }
  
  return socket
}

// 监听订单创建事件
export const onOrderCreated = (callback) => {
  if (socket) {
    socket.on('orderCreated', callback)
  }
}

// 移除订单创建事件监听
export const offOrderCreated = (callback) => {
  if (socket) {
    socket.off('orderCreated', callback)
  }
}

// 监听用户状态变更事件
export const onUserStatusChanged = (callback) => {
  if (socket) {
    socket.on('userStatusChanged', callback)
  }
}

// 移除用户状态变更事件监听
export const offUserStatusChanged = (callback) => {
  if (socket) {
    socket.off('userStatusChanged', callback)
  }
}

// 监听新公告事件
export const onNewAnnouncement = (callback) => {
  if (socket) {
    socket.on('newAnnouncement', callback)
  }
}

// 移除新公告事件监听
export const offNewAnnouncement = (callback) => {
  if (socket) {
    socket.off('newAnnouncement', callback)
  }
}

// 监听新订单事件
export const onNewOrder = (callback) => {
  if (socket) {
    socket.on('newOrder', callback)
  }
}
// 移除新订单事件监听
export const offNewOrder = (callback) => {
  if (socket) {
    socket.off('newOrder', callback)
  }
}

// 监听订单状态变更事件
export const onOrderStatusChanged = (callback) => {
  if (socket) {
    socket.on('orderStatusChanged', callback)
  }
}
export const offOrderStatusChanged = (callback) => {
  if (socket) {
    socket.off('orderStatusChanged', callback)
  }
}

export default request